package com.gzc.just.play.last.war.sceneserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.sceneserver.battle.BattleManager;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 玩家状态处理器
 * 处理获取玩家状态的消息
 */
@Component
public class PlayerStatusHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(PlayerStatusHandler.class);
    
    @Autowired
    private BattleManager battleManager;
    
    private static final int PLAYER_STATUS = 1007;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从上下文中获取玩家ID
        io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
        Long playerId = ctx.channel().attr(playerIdKey).get();
        if (playerId == null) {
            logger.error("Player ID not found in context, cannot process player status message");
            return;
        }
        
        // 如果消息中指定了其他玩家ID，则获取指定玩家状态；否则获取自己的状态
        Long targetPlayerId = extractTargetPlayerId(message);
        if (targetPlayerId == null) {
            targetPlayerId = playerId;
        }
        
        // 获取玩家状态
        Map<String, Object> playerStatus = battleManager.getPlayerStatus(targetPlayerId);
        
        // 发送玩家状态响应
        if (playerStatus != null) {
            sendPlayerStatusResponse(ctx, playerStatus, true, "Player status retrieved successfully");
            logger.info("Player {} requested status of player {}", playerId, targetPlayerId);
        } else {
            // 如果状态为空，可能是玩家不存在或不在任何战斗中
            Map<String, Object> emptyStatus = Map.of(
                "playerId", targetPlayerId,
                "inBattle", false,
                "battleId", -1,
                "playerName", "Unknown"
            );
            sendPlayerStatusResponse(ctx, emptyStatus, true, "Player not in any battle");
            logger.info("Player {} requested status of player {}, but player is not in any battle", 
                       playerId, targetPlayerId);
        }
    }
    
    private Long extractTargetPlayerId(Object message) {
        // 实际实现中应该从消息对象中解析目标玩家ID
        // 这里返回null表示获取自己的状态
        return null;
    }
    
    private void sendPlayerStatusResponse(ChannelHandlerContext ctx, Map<String, Object> playerStatus, 
                                         boolean success, String message) {
        // 实际实现中应该构造并发送玩家状态响应消息
        logger.info("Sending player status response: success={}, message={}", success, message);
        
        // 示例：打印玩家状态内容（实际实现中应该将状态序列化为响应消息）
        if (success) {
            logger.debug("Player status content:");
            logger.debug("Player ID: {}", playerStatus.get("playerId"));
            logger.debug("Player Name: {}", playerStatus.get("playerName"));
            logger.debug("In Battle: {}", playerStatus.get("inBattle"));
            logger.debug("Battle ID: {}", playerStatus.get("battleId"));
            logger.debug("Battle Name: {}", playerStatus.get("battleName"));
            logger.debug("Battle Status: {}", playerStatus.get("battleStatus"));
        }
    }

    @Override
    public int getMessageId() {
        return PLAYER_STATUS;
    }
    
    @Override
    public String getName() {
        return "PlayerStatusHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}